/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.boot.web.reactive.logger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.util.UriComponentsBuilder;

import com.iiifi.kite.boot.properties.KiteRequestLogProperties;
import com.iiifi.kite.core.util.StringUtils;
import com.iiifi.kite.launcher.enums.KiteLogLevel;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * webflux 日志请求记录
 *
 * @author kite@iiifi.com 花朝
 */
@Slf4j
@RequiredArgsConstructor
public class ReactiveRequestLogFilter implements WebFilter {
    private final KiteRequestLogProperties properties;
    private final RequestLogExclusiveRule exclusiveRule;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        KiteLogLevel level = properties.getLevel();
        // 日志没有开启直接放行
        if (KiteLogLevel.NONE == level) {
            return chain.filter(exchange);
        }

        ServerHttpRequest request = exchange.getRequest();
        // 打印请求路径
        String path = request.getPath().pathWithinApplication().value();
        // 排除请求
        if (exclusiveRule.excluded(path)) {
            return chain.filter(exchange);
        }

        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String requestURI = UriComponentsBuilder.fromPath(path).queryParams(queryParams).build().toUriString();

        // 构建成一条长 日志，避免并发下日志错乱
        StringBuilder beforeReqLog = new StringBuilder(300);
        // 日志参数
        List<Object> beforeReqArgs = new ArrayList<>();
        beforeReqLog.append("\n\n================  Request Start  ================\n");
        // 打印路由
        beforeReqLog.append("===> {}: {}\n");
        // 参数
        String requestMethod = request.getMethodValue();
        beforeReqArgs.add(requestMethod);
        beforeReqArgs.add(requestURI);

        // 打印请求头
        if (KiteLogLevel.HEADERS.lte(level)) {
            HttpHeaders headers = request.getHeaders();
            headers.forEach((headerName, headerValue) -> {
                beforeReqLog.append("===Headers===  {} : {}\n");
                beforeReqArgs.add(headerName);
                beforeReqArgs.add(StringUtils.join(headerValue));
            });
        }
        beforeReqLog.append("================   Request End   ================\n");
        // 打印执行时间
        long startNs = System.nanoTime();
        log.info(beforeReqLog.toString(), beforeReqArgs.toArray());
        // filter 执行后的日志
        StringBuilder afterReqLog = new StringBuilder(200);
        afterReqLog.append("\n\n================  Response Start  ================\n");
        try {
            return chain.filter(exchange);
        } finally {
            long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
            // webflux，这里打印的时间没太大意义
            afterReqLog.append("<=== {}: {} ({} ms)\n");
            afterReqLog.append("================   Response End   ================\n");
            log.info(afterReqLog.toString(), requestMethod, requestURI, tookMs);
        }

    }

}
